<template>
  <el-drawer
    v-model="dialogVisible"
    :title="dialogTitle"
    direction="rtl"
    size="30%"
  >
    <el-form
      ref="formRef"
      :model="tableItem"
      :rules="rules"
      label-width="120px"
      :disabled="!isDisabled"
    >
      <el-form-item label="用途" prop="usage">
        <el-select
          v-model="tableItem.usage"
          placeholder="请选择用途"
          style="width: 100%"
          @change="handleUsageChange"
        >
          <el-option label="自用" value="自用" />
          <el-option label="公摊" value="公摊" />
        </el-select>
      </el-form-item>

      <el-form-item label="组别名称" prop="groupName">
        <el-input v-model="tableItem.groupName" placeholder="请输入组别名称" />
      </el-form-item>

      <el-form-item label="组别编号" prop="groupNumber">
        <el-autocomplete
          v-model="tableItem.groupNumber"
          :fetch-suggestions="queryGroupNumbers"
          placeholder="请输入编号进行搜索"
          style="width: 100%"
          :trigger-on-focus="false"
          @blur="handleGroupNumberBlur"
          @select="handleGroupNumberSelect"
          v-loading="checkingGroupNumber"
          clearable
        >
          <template #default="{ item }">
            <div class="group-suggestion-item">
              <div class="group-number">{{ item.groupNumber }}</div>
              <div class="group-info">
                <span class="group-name">{{ item.groupName }}</span>
                <span class="meter-count">{{ item.meterCount }}个水表</span>
                <span class="unit-price">{{ item.unitPrice }}元/吨</span>
              </div>
            </div>
          </template>
        </el-autocomplete>
        <!-- 显示已存在分组的提示信息 -->
        <div v-if="existingGroupInfo && showImportOption" class="existing-group-info">
          <el-alert
            :title="`检测到已存在的公摊分组: ${existingGroupInfo.groupName}`"
            type="info"
            :closable="false"
            show-icon
          >
            <template #default>
              <div class="group-details">
                <p><strong>分组名称:</strong> {{ existingGroupInfo.groupName }}</p>
                <p><strong>水表数量:</strong> {{ existingGroupInfo.meterCount }} 个</p>
                <p><strong>当前单价:</strong> {{ existingGroupInfo.unitPrice }} 元/吨</p>
                <p><strong>水表列表:</strong> {{ existingGroupInfo.meterNames.join(', ') }}</p>
              </div>
              <div class="import-actions">
                <el-button
                  type="primary"
                  size="small"
                  @click="importExistingGroup"
                  :loading="isImporting"
                >
                  导入现有分组数据
                </el-button>
                <el-button size="small" @click="clearImportOption">
                  手动创建新分组
                </el-button>
              </div>
            </template>
          </el-alert>
        </div>
      </el-form-item>

      <el-form-item label="计费单价" prop="unitPrice">
        <el-input-number
          v-model="tableItem.unitPrice"
          :precision="2"
          :step="0.01"
          :min="0"
          style="width: 100%"
          controls-position="right"
        >
          <template #suffix>元/吨</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="比例" prop="proportion">
        <el-input-number
          v-model="tableItem.proportion"
          :precision="1"
          :step="0.1"
          :min="0"
          :max="100"
          style="width: 100%"
          controls-position="right"
        >
          <template #suffix>%</template>
        </el-input-number>
      </el-form-item>

      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="tableItem.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息"
        />
      </el-form-item>
    </el-form>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button
          v-if="dialogStatus !== 'view'"
          type="primary"
          @click="handleSubmit"
        >
          确定
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, computed } from "vue";
import { ElMessage } from "element-plus";

// 定义接口类型
interface ExistingGroupInfo {
  groupName: string;
  groupNumber: string;
  usage: string;
  unitPrice: number;
  proportion: number;
  meterCount: number;
  meterNames: string[];
  meterData: Array<{
    id: string;
    equip_name: string;
    CurrentWater: number;
    HistoricalWater: number;
    WatermeterLocation: string;
  }>;
  remark: string;
}

const emit = defineEmits(["listChange"]);

const dialogVisible = ref(false);
const dialogStatus = ref("create"); // create, edit, view
const isDisabled = ref(true);
const groupId = ref("");
const currentProjectId = ref(""); // 当前选中的项目ID

const formRef = ref();

const tableItem = reactive({
  groupName: "",
  groupNumber: "",
  usage: "",
  unitPrice: 0,
  proportion: 0,
  remark: ""
});

// 新增响应式数据用于组别编号检测和导入功能
const existingGroupInfo = ref<ExistingGroupInfo | null>(null); // 存储已存在的分组信息
const showImportOption = ref(false); // 是否显示导入选项
const isImporting = ref(false); // 导入状态
const checkingGroupNumber = ref(false); // 检查组别编号状态

// 设置当前项目ID的方法
const setProjectId = (projectId: string) => {
  currentProjectId.value = projectId;
};

const rules = {
  groupName: [
    { required: true, message: "请输入组别名称", trigger: "blur" }
  ],
  groupNumber: [
    { required: false, message: "请输入组别编号", trigger: "blur" }
  ],
  usage: [
    { required: true, message: "请选择用途", trigger: "change" }
  ],
  unitPrice: [
    { required: true, message: "请输入计费单价", trigger: "blur" }
  ],
  proportion: [
    { required: true, message: "请输入比例", trigger: "blur" }
  ]
};

const dialogTitle = computed(() => {
  switch (dialogStatus.value) {
    case "create":
      return "新增分组";
    case "edit":
      return "编辑分组";
    case "view":
      return "查看分组";
    default:
      return "分组管理";
  }
});

// 处理用途变化
const handleUsageChange = (value: string) => {
  // 当用途改变时，清除导入相关状态
  clearImportOption();

  // 如果不是公摊用途，隐藏导入选项
  if (value !== "公摊") {
    showImportOption.value = false;
    existingGroupInfo.value = null;
  }
};

// 处理组别编号失焦事件
const handleGroupNumberBlur = async () => {
  const groupNumber = tableItem.groupNumber?.trim();

  // 只有在公摊用途且有组别编号时才检查
  if (tableItem.usage !== "公摊" || !groupNumber) {
    clearImportOption();
    return;
  }

  // 如果是编辑模式，不需要检查导入
  if (dialogStatus.value === "edit") {
    return;
  }

  await checkGroupNumberExists(groupNumber);
};

// 检查组别编号是否存在
const checkGroupNumberExists = async (groupNumber: string) => {
  checkingGroupNumber.value = true;

  try {
    // 模拟API调用检查组别编号
    const response = await mockCheckGroupNumberAPI(groupNumber);

    if (response.exists && response.groupInfo) {
      // 组别编号存在，显示导入选项
      existingGroupInfo.value = response.groupInfo;
      showImportOption.value = true;

      ElMessage.info(
        `检测到组别编号 "${groupNumber}" 已存在，您可以选择导入现有分组数据`
      );
    } else {
      // 组别编号不存在，清除导入选项
      clearImportOption();
    }
  } catch (error) {
    console.error("检查组别编号失败:", error);
    ElMessage.error("检查组别编号失败，请稍后重试");
    clearImportOption();
  } finally {
    checkingGroupNumber.value = false;
  }
};

// 模拟检查组别编号的API（水表专用数据）
const mockCheckGroupNumberAPI = (groupNumber: string): Promise<{ exists: boolean; groupInfo: ExistingGroupInfo | null }> => {
  return new Promise((resolve) => {
    setTimeout(() => {
      // 模拟已存在的公摊分组数据（水表）
      const existingGroups: Record<string, ExistingGroupInfo> = {
        S001: {
          groupName: "公共区域用水",
          groupNumber: "S001",
          usage: "公摊",
          unitPrice: 3.85,
          proportion: 40.0,
          meterCount: 4,
          meterNames: ["sw30001", "sw30002", "sw30003", "sw30004"],
          meterData: [
            {
              id: "sw30001",
              equip_name: "sw30001",
              CurrentWater: 125.8,
              HistoricalWater: 98.2,
              WatermeterLocation: "F1公共卫生间"
            },
            {
              id: "sw30002",
              equip_name: "sw30002",
              CurrentWater: 89.5,
              HistoricalWater: 72.1,
              WatermeterLocation: "F2公共卫生间"
            },
            {
              id: "sw30003",
              equip_name: "sw30003",
              CurrentWater: 156.2,
              HistoricalWater: 128.9,
              WatermeterLocation: "F3公共卫生间"
            },
            {
              id: "sw30004",
              equip_name: "sw30004",
              CurrentWater: 78.9,
              HistoricalWater: 65.4,
              WatermeterLocation: "地下室公共区域"
            }
          ],
          remark: "公共区域用水分摊"
        },
        S002: {
          groupName: "绿化用水",
          groupNumber: "S002",
          usage: "公摊",
          unitPrice: 2.95,
          proportion: 20.0,
          meterCount: 2,
          meterNames: ["sw40001", "sw40002"],
          meterData: [
            {
              id: "sw40001",
              equip_name: "sw40001",
              CurrentWater: 245.6,
              HistoricalWater: 198.3,
              WatermeterLocation: "东侧绿化带"
            },
            {
              id: "sw40002",
              equip_name: "sw40002",
              CurrentWater: 189.4,
              HistoricalWater: 156.7,
              WatermeterLocation: "西侧绿化带"
            }
          ],
          remark: "园区绿化用水分摊"
        },
        S003: {
          groupName: "消防用水",
          groupNumber: "S003",
          usage: "公摊",
          unitPrice: 4.20,
          proportion: 15.0,
          meterCount: 3,
          meterNames: ["sw50001", "sw50002", "sw50003"],
          meterData: [
            {
              id: "sw50001",
              equip_name: "sw50001",
              CurrentWater: 68.2,
              HistoricalWater: 68.2,
              WatermeterLocation: "消防水池补水"
            },
            {
              id: "sw50002",
              equip_name: "sw50002",
              CurrentWater: 45.8,
              HistoricalWater: 45.8,
              WatermeterLocation: "消防栓系统"
            },
            {
              id: "sw50003",
              equip_name: "sw50003",
              CurrentWater: 32.1,
              HistoricalWater: 32.1,
              WatermeterLocation: "喷淋系统"
            }
          ],
          remark: "消防系统用水分摊"
        }
      };

      const groupInfo = existingGroups[groupNumber];

      resolve({
        exists: !!groupInfo,
        groupInfo: groupInfo || null
      });
    }, 800); // 模拟网络延迟
  });
};

// 导入现有分组数据
const importExistingGroup = async () => {
  if (!existingGroupInfo.value) {
    ElMessage.error("没有可导入的分组数据");
    return;
  }

  isImporting.value = true;

  try {
    // 模拟导入过程
    await new Promise((resolve) => setTimeout(resolve, 1000));

    // 导入分组的基础信息，但保留用户输入的分组名称和比例
    const currentGroupName = tableItem.groupName;
    const currentProportion = tableItem.proportion;

    // 填充表单数据
    Object.assign(tableItem, {
      groupNumber: existingGroupInfo.value.groupNumber,
      usage: existingGroupInfo.value.usage,
      unitPrice: existingGroupInfo.value.unitPrice,
      remark: existingGroupInfo.value.remark
    });

    // 如果用户还没有输入分组名称，使用现有的
    if (!currentGroupName) {
      tableItem.groupName = existingGroupInfo.value.groupName;
    } else {
      tableItem.groupName = currentGroupName;
    }

    // 如果用户还没有输入比例，使用现有的
    if (!currentProportion) {
      tableItem.proportion = existingGroupInfo.value.proportion;
    } else {
      tableItem.proportion = currentProportion;
    }

    ElMessage.success(
      `成功导入分组数据！包含 ${existingGroupInfo.value.meterCount} 个水表`
    );

    // 隐藏导入选项
    showImportOption.value = false;
  } catch (error) {
    console.error("导入分组数据失败:", error);
    ElMessage.error("导入分组数据失败，请稍后重试");
  } finally {
    isImporting.value = false;
  }
};

// 查询组别编号建议列表
const queryGroupNumbers = (queryString: string, callback: (suggestions: any[]) => void) => {
  if (!queryString || tableItem.usage !== '公摊') {
    callback([]);
    return;
  }

  // 模拟搜索已存在的公摊分组（水表）
  const allGroups = [
    {
      groupNumber: 'S001',
      groupName: '公共区域用水',
      meterCount: 4,
      unitPrice: 3.85,
      usage: '公摊'
    },
    {
      groupNumber: 'S002', 
      groupName: '绿化用水',
      meterCount: 2,
      unitPrice: 2.95,
      usage: '公摊'
    },
    {
      groupNumber: 'S003',
      groupName: '消防用水',
      meterCount: 3,
      unitPrice: 4.20,
      usage: '公摊'
    },
    {
      groupNumber: 'S004',
      groupName: '空调冷却水',
      meterCount: 5,
      unitPrice: 3.50,
      usage: '公摊'
    },
    {
      groupNumber: 'S005',
      groupName: '清洁用水',
      meterCount: 2,
      unitPrice: 3.20,
      usage: '公摊'
    }
  ];

  // 根据输入内容过滤
  const filtered = allGroups.filter(group => 
    group.groupNumber.toLowerCase().includes(queryString.toLowerCase()) ||
    group.groupName.toLowerCase().includes(queryString.toLowerCase())
  );

  callback(filtered);
};

// 处理组别编号选择
const handleGroupNumberSelect = (item: any) => {
  tableItem.groupNumber = item.groupNumber;
  // 选择后自动检查是否存在
  setTimeout(() => {
    checkGroupNumberExists(item.groupNumber);
  }, 100);
};

// 清除导入选项
const clearImportOption = () => {
  showImportOption.value = false;
  existingGroupInfo.value = null;
  isImporting.value = false;
};

const reset = () => {
  Object.assign(tableItem, {
    groupName: "",
    groupNumber: "",
    usage: "",
    unitPrice: 0,
    proportion: 0,
    remark: ""
  });
  formRef.value?.clearValidate();
  clearImportOption();
};

const handleSubmit = () => {
  formRef.value?.validate((valid: boolean) => {
    if (valid) {
      if (dialogStatus.value === "create") {
        console.log("创建水表分组:", tableItem);

        // 如果是导入的分组，包含水表数据信息
        if (existingGroupInfo.value) {
          console.log("导入的水表数据:", existingGroupInfo.value.meterData);
          ElMessage.success(
            `分组创建成功！已导入 ${existingGroupInfo.value.meterCount} 个水表`
          );
        } else {
          ElMessage.success("分组创建成功！");
        }
      } else if (dialogStatus.value === "edit") {
        console.log("编辑水表分组:", tableItem, "分组ID:", groupId.value);
        ElMessage.success("分组编辑成功！");
      }

      dialogVisible.value = false;
      emit("listChange");
    }
  });
};

defineExpose({
  dialogVisible,
  dialogStatus,
  isDisabled,
  groupId,
  tableItem,
  reset,
  setProjectId
});
</script>

<style lang="scss" scoped>
.existing-group-info {
  margin-top: 8px;

  .group-details {
    margin-bottom: 12px;

    p {
      margin: 4px 0;
      font-size: 13px;
      color: #606266;

      strong {
        color: #303133;
      }
    }
  }

  .import-actions {
    display: flex;
    gap: 8px;
    margin-top: 8px;
  }
}

:deep(.el-alert__content) {
  padding-right: 0;
}

:deep(.el-input-number) {
  width: 100%;
}

.group-suggestion-item {
  padding: 8px 0;
  
  .group-number {
    font-weight: bold;
    color: #409eff;
    font-size: 14px;
    margin-bottom: 4px;
  }
  
  .group-info {
    display: flex;
    gap: 12px;
    font-size: 12px;
    color: #666;
    
    .group-name {
      color: #303133;
      font-weight: 500;
    }
    
    .meter-count {
      color: #67c23a;
    }
    
    .unit-price {
      color: #e6a23c;
    }
  }
}
</style>
